package model

import (
	j_log "config-client-v1/init/j-log"
	"config-client-v1/utils/tools"
	"fmt"
)

// RCFormula 量程转换公式
type RCFormula struct {
	ID       int    `json:"id" gorm:"column:id"`
	Name     string `json:"name" gorm:"name"`
	Function string `json:"function" gorm:"function"`
	Desc     string `json:"desc" gorm:"desc"`
	Detail   string `json:"detail" gorm:"detail"`
}

func (t *RCFormula) TableName() string {
	return "range_conversion_formula"
}

func GetRCFormulaMap() (m map[int]*RCFormula, err error) {
	m = make(map[int]*RCFormula)
	list := make([]*RCFormula, 0)
	err = DB.Where("1 = 1").Limit(5000).Find(&list).Error
	if err != nil {
		j_log.LogError([]interface{}{"GetRCFormulaMap", err})
		return
	}
	for _, row := range list {
		m[row.ID] = row
	}
	return
}

func RangeValueConvert(value float64, formulaID int) (res float64) {
	if formulaID <= 0 {
		return value
	}
	formula, ok := RCFormulaMap[formulaID]
	if !ok {
		j_log.LogWarning([]interface{}{fmt.Sprintf("未找到量程转换公式, 返回0值, formula_id=%d", formulaID)})
		return 0
	}
	switch formula.Function {
	case "ModbusRTUTemperatureConvert":
		res = ModbusRTUTemperatureConvert(value)
		res = tools.RoundFloat(res, 2)
	case "ModbusRTUHumidityConvert":
		res = ModbusRTUHumidityConvert(value)
		res = tools.RoundFloat(res, 2)
	default:
		j_log.LogWarning([]interface{}{fmt.Sprintf("未定义量程转换公式, 返回0值, Function=%s", formula.Function)})
		return 0
	}
	return
}
func ModbusRTUTemperatureConvert(value float64) (res float64) {
	if value < 10000 {
		res = value * 0.1
	} else {
		res = -1 * (value - 10000) * 0.1
	}
	return
}

func ModbusRTUHumidityConvert(value float64) (res float64) {
	res = value * 0.1
	return
}
